package netty;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable<Object> {
    private ChannelHandlerContext ctx;
    private String result;//返回结果
    private String pars;//传参数

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.ctx=ctx;
        System.out.println("客户端连接");
    }

    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        result = msg.toString();
        System.out.println("返回结果"+result);
        System.out.println("参数"+msg);
        notify();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    public synchronized Object call() throws Exception {
        ctx.writeAndFlush(pars);
        System.out.println("向服务器写了"+pars);
        wait();
        return result;
    }

    public void setPars(String pars) {
        this.pars = pars;
    }
}
